{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分层的双端 GRU 模型。title部分不变，content部分使用分层。每部分取长度为 30。只用一层的 bigru.\n",
    "\n",
    "两部分的输出用 fc+bn 层拼接。\n",
    "\n",
    "- doc_len: 每个文档的句子数；\n",
    "- sent_len: 每个句子的词数量；\n",
    "- embedding_size: 词向量长度。\n",
    "\n",
    "X_inputs.shape=[batch_size, doc_len, sent_len] ->(0.embedding)-> sent_inputs.shape=[batch_size, doc_len, sent_len, embedding_size] \n",
    "\n",
    "sentence_encoder:每个句子得到一个向量:<br/>\n",
    "sent_inputs ->(reshape)-> [batch_size×doc_len, sent_len, embedding_size] ->(bigru+attention)-> doc_inputs:[batch_size×doc_len, hidden_size×2]\n",
    "\n",
    "doc_encoder: 每个文档得到一个向量：<br/>\n",
    "doc_inputs:[batch_size×doc_len, hidden_size×2] ->(reshpe)-> [batch_size, doc_len, hidden_size×2] ->(bigru+attention)-> doc_outputs:[batch_size, hidden_size*2]\n",
    "\n",
    "sigmoig_output_layer.\n",
    "\n",
    "参考代码： \n",
    "\n",
    "https://github.com/yongyehuang/deep-text-classifier/blob/master/HAN_model.py 其中attention最后加权的地方应该写错了\n",
    "\n",
    "https://github.com/indiejoseph/doc-han-att/blob/master/model.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting ...\n",
      "Prepared, costed time 6.65243 s.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt \n",
    "import pickle\n",
    "import os\n",
    "import sys\n",
    "import shutil\n",
    "import time\n",
    "\n",
    "time0 = time.time()\n",
    "print('Starting ...')\n",
    "model_name = 'han-bigru-title-content-256-30'                    # 模型名称\n",
    "W_embedding = np.load('../data/W_embedding.npy')            # 导入预训练好的词向量\n",
    "model_path = '../ckpt/' + model_name + '/'                  # 模型保存位置\n",
    "summary_path = '../summary/' + model_name + '/'             # summary 位置\n",
    "result_path = '../result/' + model_name + '.csv'            # result.csv 位置\n",
    "scores_path = '../scores/' + model_name + '.npy'            # scores.npy 位置\n",
    "save_path = '../data/'\n",
    "\n",
    "if not os.path.exists(model_path):\n",
    "    os.makedirs(model_path)         \n",
    "model_path = model_path + 'model.ckpt'\n",
    "# if os.path.exists(summary_path):   # 删除原来的 summary 文件，避免重合\n",
    "#     shutil.rmtree(summary_path)\n",
    "# os.makedirs(summary_path)          # 然后再次创建\n",
    "\n",
    "# ##################### config ######################\n",
    "# title 部分 attention-bigru-512 \n",
    "title_len = n_step1 = 30                  # title 长度\n",
    "# content 部分 han-bigru-512\n",
    "doc_len = 10                   # 每个文档的句子数\n",
    "sent_len = 30                 # 每个句子的词数\n",
    "# 其他参数\n",
    "input_size = embedding_size = 256       # 字向量长度\n",
    "n_class = 1999\n",
    "hidden_size = 256    # 隐含层节点数\n",
    "fc_hidden_size = 1024                   # fc 层节点数\n",
    "title_attention_size = sent_attention_size = doc_attention_size = hidden_size * 2\n",
    "n_layer = 1        # bi-gru 层数\n",
    "max_grad_norm = 5.0  # 最大梯度（超过此值的梯度将被裁剪）\n",
    "global_step = 0\n",
    "valid_num = 100000\n",
    "seed_num = 13\n",
    "te_batch_size = 128 \n",
    "tr_batch_size = 128 \n",
    "print('Prepared, costed time %g s.' % (time.time() - time0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Building model ...\n",
      "Finished creating the han-bi-gru model.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "config = tf.ConfigProto()\n",
    "config.gpu_options.allow_growth = True\n",
    "sess = tf.Session(config=config)\n",
    "from tensorflow.contrib import rnn\n",
    "import tensorflow.contrib.layers as layers\n",
    "\n",
    "'''\n",
    "HAN 模型，知乎问题多标签分类。\n",
    "'''\n",
    "\n",
    "print('Building model ...')\n",
    "lr = tf.placeholder(tf.float32)\n",
    "keep_prob = tf.placeholder(tf.float32, [])\n",
    "batch_size = tf.placeholder(tf.int32, [])  # 注意类型必须为 tf.int32\n",
    "tst = tf.placeholder(tf.bool)\n",
    "n_updates = tf.placeholder(tf.int32)      # training iteration,传入 bn 层\n",
    "update_emas = list()   # BN 层中所有的更新操作\n",
    "\n",
    "\n",
    "def weight_variable(shape, name):\n",
    "    \"\"\"Create a weight variable with appropriate initialization.\"\"\"\n",
    "    initial = tf.truncated_normal(shape, stddev=0.1)\n",
    "    return tf.Variable(initial, name=name)\n",
    "\n",
    "def bias_variable(shape, name):\n",
    "    \"\"\"Create a bias variable with appropriate initialization.\"\"\"\n",
    "    initial = tf.constant(0.1, shape=shape)\n",
    "    return tf.Variable(initial, name=name)\n",
    "\n",
    "def batchnorm(Ylogits, is_test, num_updates, offset, convolutional=False):\n",
    "    \"\"\"batchnormalization.\n",
    "    Args:\n",
    "        Ylogits: 1D向量或者是3D的卷积结果。\n",
    "        num_updates: 迭代的global_step\n",
    "        offset：表示beta，全局均值；在 RELU 激活中一般初始化为 0.1。\n",
    "        scale：表示lambda，全局方差；在 sigmoid 激活中需要，这 RELU 激活中作用不大。\n",
    "        m: 表示batch均值；v:表示batch方差。\n",
    "        bnepsilon：一个很小的浮点数，防止除以 0.\n",
    "    Returns:\n",
    "        Ybn: 和 Ylogits 的维度一样，就是经过 Batch Normalization 处理的结果。\n",
    "        update_moving_everages：更新mean和variance，主要是给最后的 test 使用。\n",
    "    \"\"\"\n",
    "    exp_moving_avg = tf.train.ExponentialMovingAverage(0.999, num_updates) # adding the iteration prevents from averaging across non-existing iterations\n",
    "    bnepsilon = 1e-5\n",
    "    if convolutional:\n",
    "        mean, variance = tf.nn.moments(Ylogits, [0, 1, 2])\n",
    "    else:\n",
    "        mean, variance = tf.nn.moments(Ylogits, [0])\n",
    "    update_moving_everages = exp_moving_avg.apply([mean, variance])\n",
    "    m = tf.cond(is_test, lambda: exp_moving_avg.average(mean), lambda: mean)\n",
    "    v = tf.cond(is_test, lambda: exp_moving_avg.average(variance), lambda: variance)\n",
    "    Ybn = tf.nn.batch_normalization(Ylogits, m, v, offset, None, bnepsilon)\n",
    "    return Ybn, update_moving_everages\n",
    "\n",
    "def gru_cell():\n",
    "    with tf.variable_scope('gru_cell'):\n",
    "        cell = rnn.GRUCell(hidden_size, reuse=tf.get_variable_scope().reuse)\n",
    "    return rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)\n",
    "  \n",
    "def bi_gru(inputs, seg_num=batch_size):\n",
    "    \"\"\"build the bi-GRU network. Return the encoder represented vector.\n",
    "    n_step: 句子的词数量；或者文档的句子数。\n",
    "    seg_num: 序列的数量，原本应该为 batch_size, 但是这里将 batch_size 个 doc展开成很多个句子。\n",
    "    \"\"\"\n",
    "    cells_fw = [gru_cell() for _ in range(n_layer)]\n",
    "    cells_bw = [gru_cell() for _ in range(n_layer)]\n",
    "    initial_states_fw = [cell_fw.zero_state(seg_num, tf.float32) for cell_fw in cells_fw]\n",
    "    initial_states_bw = [cell_bw.zero_state(seg_num, tf.float32) for cell_bw in cells_bw] \n",
    "    outputs, _, _ = rnn.stack_bidirectional_dynamic_rnn(cells_fw, cells_bw, inputs, \n",
    "                        initial_states_fw = initial_states_fw, initial_states_bw = initial_states_bw, dtype=tf.float32)\n",
    "    # outputs: Output Tensor shaped: seg_num, max_time, layers_output]，其中layers_output=hidden_size * 2 在这里。\n",
    "    return outputs\n",
    "    \n",
    "    \n",
    "def task_specific_attention(inputs, output_size,\n",
    "                            initializer=layers.xavier_initializer(),\n",
    "                            activation_fn=tf.tanh, scope=None):\n",
    "    \"\"\"\n",
    "    Performs task-specific attention reduction, using learned\n",
    "    attention context vector (constant within task of interest).\n",
    "    Args:\n",
    "        inputs: Tensor of shape [batch_size, units, input_size]\n",
    "            `input_size` must be static (known)\n",
    "            `units` axis will be attended over (reduced from output)\n",
    "            `batch_size` will be preserved\n",
    "        output_size: Size of output's inner (feature) dimension\n",
    "    Returns:\n",
    "        outputs: Tensor of shape [batch_size, output_dim].\n",
    "    \"\"\"\n",
    "    assert len(inputs.get_shape()) == 3 and inputs.get_shape()[-1].value is not None\n",
    "    with tf.variable_scope(scope or 'attention') as scope:\n",
    "        # u_w, attention 向量\n",
    "        attention_context_vector = tf.get_variable(name='attention_context_vector',\n",
    "                                                   shape=[output_size],\n",
    "                                                   initializer=initializer,\n",
    "                                                   dtype=tf.float32)\n",
    "        # 全连接层，把 h_i 转为 u_i ， shape= [batch_size, units, input_size] -> [batch_size, units, output_size]\n",
    "        input_projection = layers.fully_connected(inputs, output_size,\n",
    "                                                  activation_fn=activation_fn,\n",
    "                                                  scope=scope)\n",
    "        # 输出 [batch_size, units]\n",
    "        vector_attn = tf.reduce_sum(tf.multiply(input_projection, attention_context_vector), axis=2, keep_dims=True)\n",
    "        attention_weights = tf.nn.softmax(vector_attn, dim=1)   \n",
    "        tf.summary.histogram('attention_weigths', attention_weights)\n",
    "        weighted_projection = tf.multiply(inputs, attention_weights)   # ???源代码,原文应该是对 hi 加权！！\n",
    "        outputs = tf.reduce_sum(weighted_projection, axis=1)\n",
    "        return outputs  # 输出 [batch_size, units]\n",
    "\n",
    "\n",
    "with tf.name_scope('Inputs'):\n",
    "    X1_inputs = tf.placeholder(tf.int64, [None, title_len], name='X1_inputs')\n",
    "    X2_inputs = tf.placeholder(tf.int64, [None, doc_len*sent_len], name='X2_inputs')\n",
    "    y_inputs = tf.placeholder(tf.float32, [None, n_class], name='y_input')    \n",
    "\n",
    "with tf.name_scope('embedding'):\n",
    "    embedding = tf.get_variable(name='embedding', shape=W_embedding.shape, \n",
    "                                initializer=tf.constant_initializer(W_embedding), trainable=True)   # fine-tune\n",
    "    \n",
    "def bigru_reference(X_inputs):\n",
    "    \"\"\"双端 gru 模型。title部分。\n",
    "    Args: \n",
    "        X_inputs: tensor.shape=(batch_size, title_len)\n",
    "    Returns:\n",
    "        title_outputs: tensor.shape=(batch_size, hidden_size(*2 for bigru))\n",
    "    \"\"\"\n",
    "    inputs = tf.nn.embedding_lookup(embedding, X_inputs)\n",
    "    with tf.variable_scope('title_encoder'):  # 生成 title 的向量表示\n",
    "        title_outputs = bi_gru(inputs)\n",
    "        title_attn_outputs = task_specific_attention(title_outputs, title_attention_size)   \n",
    "    return title_attn_outputs   # shape = [batch_size, hidden_size*2]\n",
    "    \n",
    "def han_reference(X_inputs):\n",
    "    \"\"\"分层 attention 模型。content部分。\n",
    "    Args: \n",
    "        X_inputs: tensor.shape=(batch_size, doc_len*sent_len)\n",
    "    Returns:\n",
    "        doc_attn_outputs: tensor.shape=(batch_size, hidden_size(*2 for bigru))\n",
    "    \"\"\"\n",
    "    inputs = tf.nn.embedding_lookup(embedding, X_inputs)    # inputs.shape=[batch_size, doc_len*sent_len, embedding_size]\n",
    "    sent_inputs = tf.reshape(inputs,[batch_size*doc_len, sent_len, embedding_size]) # shape=(?, 40, 256)\n",
    "    with tf.variable_scope('sentence_encoder'):  # 生成句向量\n",
    "        sent_outputs = bi_gru(sent_inputs, seg_num=batch_size*doc_len)\n",
    "        sent_attn_outputs = task_specific_attention(sent_outputs, sent_attention_size) # [batch_size*doc_len, hidden_size*2]\n",
    "        with tf.variable_scope('dropout'):\n",
    "            sent_attn_outputs = tf.nn.dropout(sent_attn_outputs, keep_prob)\n",
    "    with tf.variable_scope('doc_encoder'):  # 生成句向量\n",
    "        doc_inputs = tf.reshape(sent_attn_outputs, [batch_size, doc_len, hidden_size*2])\n",
    "        doc_outputs = bi_gru(doc_inputs)  # [batch_size, doc_len, hidden_size*2]\n",
    "        doc_attn_outputs = task_specific_attention(doc_outputs, doc_attention_size) # [batch_size, hidden_size*2]\n",
    "        with tf.variable_scope('dropout'):\n",
    "            doc_attn_outputs = tf.nn.dropout(doc_attn_outputs, keep_prob)    \n",
    "    return doc_attn_outputs    # [batch_size, hidden_size*2]\n",
    "        \n",
    "\n",
    "with tf.name_scope('title_bigru'):\n",
    "    output_title = bigru_reference(X1_inputs)\n",
    "with tf.name_scope('content_han'):\n",
    "    output_content = han_reference(X2_inputs)   \n",
    "    \n",
    "with tf.name_scope('fc-bn-layer'):\n",
    "    output = tf.concat([output_title, output_content], axis=1)\n",
    "    W_fc = weight_variable([hidden_size*4, fc_hidden_size], name='Weight_fc')\n",
    "    tf.summary.histogram('W_fc', W_fc)\n",
    "    h_fc = tf.matmul(output, W_fc, name='h_fc')\n",
    "    beta_fc = tf.Variable(tf.constant(0.1, tf.float32, shape=[fc_hidden_size], name=\"beta_fc\"))\n",
    "    tf.summary.histogram('beta_fc', beta_fc)\n",
    "    fc_bn, update_ema_fc = batchnorm(h_fc, tst, n_updates, beta_fc, convolutional=False)\n",
    "    update_emas.append(update_ema_fc)\n",
    "    fc_bn_relu = tf.nn.relu(fc_bn, name=\"relu\")\n",
    "#     fc_bn_drop = tf.nn.dropout(fc_bn_relu, keep_prob)   # 不加 dropout\n",
    "    \n",
    "with tf.name_scope('out_layer'):\n",
    "    W_out = weight_variable([fc_hidden_size, n_class], name='Weight_out') \n",
    "    tf.summary.histogram('Weight_out', W_out)\n",
    "    b_out = bias_variable([n_class], name='bias_out') \n",
    "    tf.summary.histogram('bias_out', b_out)\n",
    "    y_pred = tf.nn.xw_plus_b(fc_bn_relu, W_out, b_out, name='y_pred')  #每个类别的分数 scores\n",
    "    \n",
    "with tf.name_scope('cost'):\n",
    "    cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_pred, labels=y_inputs))\n",
    "    tf.summary.scalar('cost', cost)\n",
    "    \n",
    "# ***** 优化求解 *******\n",
    "with tf.name_scope('AdamOptimizer'):\n",
    "    tvars = tf.trainable_variables()\n",
    "    grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), max_grad_norm)\n",
    "    optimizer = tf.train.AdamOptimizer(learning_rate=lr)\n",
    "    train_op = optimizer.apply_gradients( zip(grads, tvars),\n",
    "        global_step=tf.contrib.framework.get_or_create_global_step())\n",
    "    update_op = tf.group(*update_emas)   # 更新 BN 参数\n",
    "\n",
    "merged = tf.summary.merge_all() # summary\n",
    "train_writer = tf.summary.FileWriter(summary_path + 'train', sess.graph)\n",
    "test_writer = tf.summary.FileWriter(summary_path + 'test')\n",
    "print 'Finished creating the han-bi-gru model.'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loading data...\n",
      "finished loading data, time cost 101.194 s\n",
      "Finised loading data, time 125.448 s\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "sys.path.append('..')\n",
    "from data_helpers import BatchGenerator\n",
    "from data_helpers import to_categorical\n",
    "from evaluator import score_eval\n",
    "\n",
    "\n",
    "print('loading data...')\n",
    "time0 = time.time()\n",
    "X_title = np.load(save_path+'X_tr_title.npy') \n",
    "sample_num = X_title.shape[0]\n",
    "X_content = np.load(save_path+'train_segs30_content.npy')\n",
    "X_content = X_content.reshape([-1, doc_len*sent_len])\n",
    "X = np.hstack([X_title, X_content])\n",
    "y = np.load(save_path+'y_tr.npy')\n",
    "print('finished loading data, time cost %g s' % (time.time() - time0))\n",
    "# 划分验证集\n",
    "np.random.seed(seed_num)\n",
    "new_index = np.random.permutation(sample_num)\n",
    "X = X[new_index]\n",
    "y = y[new_index]\n",
    "X_valid = X[:valid_num]\n",
    "y_valid = y[:valid_num]\n",
    "# X_train = X[valid_num:]\n",
    "# y_train = y[valid_num:]\n",
    "# print('train_num=%d, valid_num=%d' % (X_train.shape[0], X_valid.shape[0]))\n",
    "\n",
    "# # 构建数据生成器\n",
    "# data_train = BatchGenerator(X_train, y_train, shuffle=True)\n",
    "# data_valid = BatchGenerator(X_valid, y_valid, shuffle=False)\n",
    "# print('X_train.shape=', X_train.shape, 'y_train.shape=', y_train.shape)\n",
    "# print('X_valid.shape=', X_valid.shape, 'y_valid.shape=', y_valid.shape)\n",
    "\n",
    "# marked_labels_list = data_valid.y.tolist() # 所有的标注结果\n",
    "# valid_data_size = data_valid.y.shape[0]\n",
    "def valid_epoch():\n",
    "    \"\"\"Testing or valid.\"\"\"\n",
    "    data_valid._index_in_epoch = 0  # 先指向第一个值\n",
    "    _batch_size = te_batch_size\n",
    "    fetches = [cost, y_pred]   \n",
    "    batch_num = int(valid_data_size / _batch_size)\n",
    "    start_time = time.time()\n",
    "    _costs = 0.0\n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    for i in xrange(batch_num):\n",
    "        X_batch, y_batch = data_valid.next_batch(_batch_size)\n",
    "        X1_batch = X_batch[:, :title_len]\n",
    "        X2_batch = X_batch[:, title_len:]\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, y_inputs:y_batch, lr:1e-5, \n",
    "                    batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "        _cost, predict_labels = sess.run(fetches, feed_dict)\n",
    "        _costs += _cost    \n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "    precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "    mean_cost = _costs / batch_num\n",
    "    return mean_cost, precision, recall, f1\n",
    "\n",
    "print('Finised loading data, time %g s' % (time.time() - time0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 训练模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.167635202407837e-05"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "0.001*(0.75**12)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EPOCH 1， lr=0.00065\n",
      "Global_step=8000: valid cost=0.00448241; p=1.24246, r=0.506086, f1=0.359609 \n",
      "===>_lr=0.0004225\n",
      "Global_step=16000: valid cost=0.00415743; p=1.32799, r=0.540933, f1=0.384367 \n",
      "===>_lr=0.000274625\n",
      "training cost=0.0049985; valid cost=0.00401547; p=1.36628, r=0.55592, f1=0.395142; speed=8409.19 s/epoch\n",
      "EPOCH 2， lr=0.000178506\n",
      "Global_step=30655: valid cost=0.00396964; p=1.38394, r=0.563619, f1=0.400509 \n",
      "('the save path is ', '../ckpt/han-bigru-title-content-256-30/model.ckpt-1')\n",
      "===>_lr=0.000116029\n"
     ]
    }
   ],
   "source": [
    "_lr = 1e-3\n",
    "max_epoch = 1\n",
    "max_max_epoch = 8  # 本例中，\n",
    "decay = 0.65\n",
    "valid_step = 8000        # 每 valid_step 就进行一次 valid 运算\n",
    "save_epoch = 1           # 每迭代 save_epoch 次保存一次模型\n",
    "tr_batch_num = int(data_train.y.shape[0] / tr_batch_size)  # 每个 epoch 中包含的 batch 数\n",
    "saver = tf.train.Saver(max_to_keep=3)           # 最多保存的模型数量\n",
    "sess.run(tf.global_variables_initializer())\n",
    "last_f1 = 0.39\n",
    "model_num = 0\n",
    "\n",
    "for epoch in xrange(max_max_epoch):\n",
    "    _lr = _lr * decay\n",
    "    print 'EPOCH %d， lr=%g' % (epoch+1, _lr)\n",
    "    time0 = time.time()\n",
    "    _costs = 0.0\n",
    "    for batch in xrange(tr_batch_num): \n",
    "        global_step += 1\n",
    "        if (batch+1) % valid_step == 0:    # 进行 valid 计算\n",
    "            valid_cost, precision, recall, f1 = valid_epoch()\n",
    "            print('Global_step=%d: valid cost=%g; p=%g, r=%g, f1=%g ' % (\n",
    "                    global_step, valid_cost, precision, recall, f1))\n",
    "            if (f1 > last_f1):\n",
    "                last_f1 = f1\n",
    "                model_num += 1\n",
    "                save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "                print('the save path is ', save_path) \n",
    "            _lr = _lr * decay\n",
    "            print('===>_lr=%g' % _lr)\n",
    "        X_batch, y_batch = data_train.next_batch(tr_batch_size)\n",
    "        X1_batch = X_batch[:, :title_len]\n",
    "        X2_batch = X_batch[:, title_len:]\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        feed_dict = {X1_inputs:X1_batch,X2_inputs:X2_batch, y_inputs:y_batch, lr:_lr,\n",
    "                    batch_size:tr_batch_size, keep_prob:0.5, tst:False, n_updates:global_step}\n",
    "        fetches = [merged, cost, train_op, update_op]\n",
    "        summary, _cost, _, _ = sess.run(fetches, feed_dict) # the cost is the mean cost of one batch\n",
    "        _costs += _cost\n",
    "        if global_step % 100:\n",
    "            train_writer.add_summary(summary, global_step)\n",
    "            X_batch, y_batch = data_valid.next_batch(tr_batch_size)\n",
    "            X1_batch = X_batch[:, :title_len]\n",
    "            X2_batch = X_batch[:, title_len:]\n",
    "            y_batch = to_categorical(y_batch)\n",
    "            feed_dict = {X1_inputs:X1_batch,X2_inputs:X2_batch, y_inputs:y_batch, lr:1e-5,\n",
    "                         batch_size:tr_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "            fetches = [merged, cost]\n",
    "            summary, _cost = sess.run(fetches, feed_dict)\n",
    "            test_writer.add_summary(summary, global_step)\n",
    "    valid_cost, precision, recall, f1 = valid_epoch()  # # 每个 epoch 进行一次验证 valid\n",
    "    mean_cost = _costs / tr_batch_num\n",
    "    print('Global_step=%d; training cost=%g; valid cost=%g; p=%g, r=%g, f1=%g; speed=%g s/epoch' % (\n",
    "        global_step, mean_cost, valid_cost, precision, recall, f1, time.time()-time0) )\n",
    "    if (f1 > last_f1):\n",
    "        last_f1 = f1\n",
    "        model_num += 1\n",
    "        save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "        print('the save path is ', save_path)       "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "valid cost=0.00429876; p=1.36063, r=0.552703, f1=0.393044; speed=5141.38 s/epoch\n"
     ]
    }
   ],
   "source": [
    "valid_cost, precision, recall, f1 = valid_epoch()  # # 每个 epoch 进行一次验证 valid\n",
    "print('valid cost=%g; p=%g, r=%g, f1=%g; speed=%g s/epoch' % (\n",
    "     valid_cost, precision, recall, f1, time.time()-time0) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('the save path is ', '../ckpt/han-bigru-title-content-256/model.ckpt-4')\n"
     ]
    }
   ],
   "source": [
    "save_path = saver.save(sess, model_path, global_step=(epoch+1))\n",
    "print('the save path is ', save_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Bi-LSTM 模型<br/>\n",
    "**batch_size=256，迭代12个epoch，基本收敛。结果： 验证集 f1=0.38618； 提交结果 0.3873186**\n",
    "- Bi-GRU 模型<br/>\n",
    "**batch_size=256，迭代15个epoch。大概在 13 个 epoch 就收敛了。结果： 验证集 f1=0.390534； 提交结果 0.39198**\n",
    "- attention-Bi-GRU 模型<br/>\n",
    "**batch_size=256，迭代18个epoch。在16个epoch收敛。结果：验证集 f1=f1=0.391734 ；提交结果 0.39310**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 若没有收敛，继续迭代"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from ../ckpt/han-bigru-title-content-256-30/model.ckpt-7\n",
      "Finished loading model.\n",
      "Global_step=138321: valid cost=0.00388571; p=1.41074, r=0.574479, f1=0.408237 \n",
      "costed time 109.284 s\n"
     ]
    }
   ],
   "source": [
    "# 导入保存好的模型\n",
    "time0 =time.time()\n",
    "saver = tf.train.Saver()\n",
    "best_model_path = model_path + '-' + str(7)  # 导入最优模型   f1=0.408237\n",
    "saver.restore(sess, best_model_path)\n",
    "print('Finished loading model.')\n",
    "valid_cost, precision, recall, f1 = valid_epoch()\n",
    "print('Global_step=%d: valid cost=%g; p=%g, r=%g, f1=%g ' % (\n",
    "        global_step, valid_cost, precision, recall, f1))\n",
    "print('costed time %g s' % (time.time()-time0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EPOCH 1， lr=2.25e-05\n",
      "Global_step=87000: valid cost=0.00389798; p=1.40806, r=0.573273, f1=0.407403 \n",
      "===>_lr=1.6875e-05\n",
      "Global_step=95000: valid cost=0.00389498; p=1.40956, r=0.573765, f1=0.407778 \n",
      "===>_lr=1.26562e-05\n",
      "Global_step=101655; training cost=0.00361811; valid cost=0.00389419; p=1.40892, r=0.573452, f1=0.407567; speed=7553.93 s/epoch\n",
      "EPOCH 2， lr=9.49219e-06\n",
      "Global_step=109655: valid cost=0.00389483; p=1.4099, r=0.574043, f1=0.407947 \n",
      "===>_lr=7.11914e-06\n",
      "Global_step=117655: valid cost=0.00389145; p=1.41003, r=0.574021, f1=0.407946 \n",
      "===>_lr=5.33936e-06\n",
      "Global_step=124310; training cost=0.00360596; valid cost=0.00389107; p=1.41058, r=0.574252, f1=0.408109; speed=7648.16 s/epoch\n",
      "EPOCH 3， lr=4.00452e-06\n",
      "Global_step=132310: valid cost=0.00389246; p=1.40998, r=0.574214, f1=0.408039 \n",
      "===>_lr=3.00339e-06\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-7-692264fb6b67>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     46\u001b[0m                          batch_size:tr_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n\u001b[1;32m     47\u001b[0m             \u001b[0mfetches\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mmerged\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcost\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 48\u001b[0;31m             \u001b[0msummary\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_cost\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msess\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfetches\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfeed_dict\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     49\u001b[0m             \u001b[0mtest_writer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_summary\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msummary\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mglobal_step\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     50\u001b[0m     \u001b[0mvalid_cost\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mprecision\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrecall\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mf1\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mvalid_epoch\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# # 每个 epoch 进行一次验证 valid\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36mrun\u001b[0;34m(self, fetches, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m    787\u001b[0m     \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    788\u001b[0m       result = self._run(None, fetches, feed_dict, options_ptr,\n\u001b[0;32m--> 789\u001b[0;31m                          run_metadata_ptr)\n\u001b[0m\u001b[1;32m    790\u001b[0m       \u001b[0;32mif\u001b[0m \u001b[0mrun_metadata\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    791\u001b[0m         \u001b[0mproto_data\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtf_session\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mTF_GetBuffer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrun_metadata_ptr\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_run\u001b[0;34m(self, handle, fetches, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m    995\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mfinal_fetches\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mfinal_targets\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    996\u001b[0m       results = self._do_run(handle, final_targets, final_fetches,\n\u001b[0;32m--> 997\u001b[0;31m                              feed_dict_string, options, run_metadata)\n\u001b[0m\u001b[1;32m    998\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    999\u001b[0m       \u001b[0mresults\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_do_run\u001b[0;34m(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m   1130\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mhandle\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1131\u001b[0m       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,\n\u001b[0;32m-> 1132\u001b[0;31m                            target_list, options, run_metadata)\n\u001b[0m\u001b[1;32m   1133\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1134\u001b[0m       return self._do_call(_prun_fn, self._session, handle, feed_dict,\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_do_call\u001b[0;34m(self, fn, *args)\u001b[0m\n\u001b[1;32m   1137\u001b[0m   \u001b[0;32mdef\u001b[0m \u001b[0m_do_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1138\u001b[0m     \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1139\u001b[0;31m       \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1140\u001b[0m     \u001b[0;32mexcept\u001b[0m \u001b[0merrors\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mOpError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1141\u001b[0m       \u001b[0mmessage\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcompat\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mas_text\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmessage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/common/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_run_fn\u001b[0;34m(session, feed_dict, fetch_list, target_list, options, run_metadata)\u001b[0m\n\u001b[1;32m   1119\u001b[0m         return tf_session.TF_Run(session, options,\n\u001b[1;32m   1120\u001b[0m                                  \u001b[0mfeed_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfetch_list\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtarget_list\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1121\u001b[0;31m                                  status, run_metadata)\n\u001b[0m\u001b[1;32m   1122\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1123\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0m_prun_fn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msession\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mhandle\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfeed_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfetch_list\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "model_num = 7\n",
    "_lr = 3e-5\n",
    "add_epoch = 3  # 本例中，\n",
    "decay = 0.75\n",
    "valid_step = 8000        # 每 valid_step 就进行一次 valid 运算\n",
    "save_epoch = 1           # 每迭代 save_epoch 次保存一次模型\n",
    "tr_batch_num = int(data_train.y.shape[0] / tr_batch_size)  # 每个 epoch 中包含的 batch 数\n",
    "saver = tf.train.Saver(max_to_keep=5)           # 最多保存的模型数量\n",
    "last_f1=0.408237\n",
    "global_step = 79000\n",
    "\n",
    "for epoch in xrange(add_epoch):\n",
    "    _lr = _lr * decay\n",
    "    print 'EPOCH %d， lr=%g' % (epoch+1, _lr)\n",
    "    time0 = time.time()\n",
    "    _costs = 0.0\n",
    "    for batch in xrange(tr_batch_num): \n",
    "        global_step += 1\n",
    "        if (batch+1) % valid_step == 0:    # 进行 valid 计算\n",
    "            valid_cost, precision, recall, f1 = valid_epoch()\n",
    "            print('Global_step=%d: valid cost=%g; p=%g, r=%g, f1=%g ' % (\n",
    "                    global_step, valid_cost, precision, recall, f1))\n",
    "            if (f1 > last_f1):\n",
    "                last_f1 = f1\n",
    "                model_num += 1\n",
    "                save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "                print('the save path is ', save_path) \n",
    "            _lr = _lr * decay\n",
    "            print('===>_lr=%g' % _lr)\n",
    "        X_batch, y_batch = data_train.next_batch(tr_batch_size)\n",
    "        X1_batch = X_batch[:, :title_len]\n",
    "        X2_batch = X_batch[:, title_len:]\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        feed_dict = {X1_inputs:X1_batch,X2_inputs:X2_batch, y_inputs:y_batch, lr:_lr,\n",
    "                    batch_size:tr_batch_size, keep_prob:0.45, tst:False, n_updates:global_step}\n",
    "        fetches = [merged, cost, train_op, update_op]\n",
    "        summary, _cost, _, _ = sess.run(fetches, feed_dict) # the cost is the mean cost of one batch\n",
    "        _costs += _cost\n",
    "        if global_step % 100:\n",
    "            train_writer.add_summary(summary, global_step)\n",
    "            X_batch, y_batch = data_valid.next_batch(tr_batch_size)\n",
    "            X1_batch = X_batch[:, :title_len]\n",
    "            X2_batch = X_batch[:, title_len:]\n",
    "            y_batch = to_categorical(y_batch)\n",
    "            feed_dict = {X1_inputs:X1_batch,X2_inputs:X2_batch, y_inputs:y_batch, lr:1e-5,\n",
    "                         batch_size:tr_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "            fetches = [merged, cost]\n",
    "            summary, _cost = sess.run(fetches, feed_dict)\n",
    "            test_writer.add_summary(summary, global_step)\n",
    "    valid_cost, precision, recall, f1 = valid_epoch()  # # 每个 epoch 进行一次验证 valid\n",
    "    mean_cost = _costs / tr_batch_num\n",
    "    print('Global_step=%d; training cost=%g; valid cost=%g; p=%g, r=%g, f1=%g; speed=%g s/epoch' % (\n",
    "        global_step, mean_cost, valid_cost, precision, recall, f1, time.time()-time0) )\n",
    "    if (f1 > last_f1):\n",
    "        last_f1 = f1\n",
    "        model_num += 1\n",
    "        save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "        print('the save path is ', save_path)       "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 本地测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "begin ...\n",
      "INFO:tensorflow:Restoring parameters from ../ckpt/han-bigru-title-content-256-30/model.ckpt-7\n",
      "Finished loading model.\n"
     ]
    }
   ],
   "source": [
    "sys.path.append('..')\n",
    "from evaluator import score_eval\n",
    "\n",
    "print('begin ...')\n",
    "# X_valid = np.load('../data/X_valid.npy')\n",
    "# 保存 本地测试的标注数据\n",
    "marked_labels_list = np.load('../data/marked_labels_list.npy')\n",
    "local_scores_path = '../local_scores/' + model_name + '.npy'\n",
    "\n",
    "# 导入保存好的模型\n",
    "saver = tf.train.Saver()\n",
    "best_model_path = model_path + '-' + str(7)  # 导入最优模型\n",
    "saver.restore(sess, best_model_path)\n",
    "print('Finished loading model.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "local predicting ...\n",
      "local valid p=1.41072, r=0.574443, f1=0.408218; speed=64.8159 s/epoch\n",
      "Writed the scores into ../local_scores/han-bigru-title-content-256-30.npy, time 71.251 s\n"
     ]
    }
   ],
   "source": [
    "local_scores_path = '../local_scores/' + model_name + '.npy'\n",
    "global_step = 800000\n",
    "# 导入测试数据\n",
    "def local_predict(scores_path=local_scores_path):\n",
    "    \"\"\"预测  valid 结果，并保存预测概率 到  scores.csv 文件中。\"\"\"\n",
    "    print('local predicting ...')\n",
    "    time0 = time.time()\n",
    "    X_te = X_valid\n",
    "    n_sample = X_te.shape[0]  # 测试样本数量\n",
    "    _batch_size = 128\n",
    "    fetches = [y_pred]   \n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    predict_scores = list()\n",
    "    for i in xrange(0, n_sample, _batch_size):\n",
    "        start = i\n",
    "        end = start+_batch_size\n",
    "        if end > n_sample:\n",
    "            end = n_sample\n",
    "            _batch_size = end - start\n",
    "        X_batch = X_te[start:end]\n",
    "        X1_batch = X_batch[:, :title_len]\n",
    "        X2_batch = X_batch[:, title_len:]\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, lr:1e-5, \n",
    "                     batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "        predict_labels = sess.run(fetches, feed_dict)[0]\n",
    "        predict_scores.append(predict_labels)\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_scores = np.asarray(predict_scores)\n",
    "    predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "    precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "    print('local valid p=%g, r=%g, f1=%g; speed=%g s/epoch' % ( precision, recall, f1, time.time()-time0) )\n",
    "    np.save(local_scores_path, predict_scores)\n",
    "    print('Writed the scores into %s, time %g s' % (local_scores_path, time.time()-time0))\n",
    "    \n",
    "local_predict()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 对测试数据进行预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from ../ckpt/han-bigru-title-content-256/model.ckpt-4\n"
     ]
    }
   ],
   "source": [
    "# 导入保存好的模型\n",
    "saver = tf.train.Saver()\n",
    "best_model_path = model_path + '-' +str(7)\n",
    "saver.restore(sess, best_model_path)\n",
    "\n",
    "result_path = '../result/' + model_name + '-epoch4.csv'            # result.csv 位置\n",
    "scores_path = '../scores/' + model_name + '-epoch4.npy'            # scores.npy 位置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 导入测试数据\n",
    "def predict():\n",
    "    \"\"\"预测测试集结果，并保存到  result.csv 文件中。\"\"\"\n",
    "    X_title = np.load(save_path+'X_te_title.npy') \n",
    "    X_content = np.load(save_path+'eval_segs30_content.npy')\n",
    "    X_content = X_content.reshape([-1, doc_len*sent_len])\n",
    "    X_te = np.hstack([X_title, X_content])\n",
    "    n_sample = X_te.shape[0]  # 测试样本数量\n",
    "    _batch_size = 1000\n",
    "    fetches = [y_pred]   \n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    predict_scores = list()\n",
    "    for i in xrange(0, n_sample, _batch_size):\n",
    "        start = i\n",
    "        end = start+_batch_size\n",
    "        if end > n_sample:\n",
    "            end = n_sample\n",
    "            _batch_size = end - start\n",
    "        X_batch = X_te[start:end]\n",
    "        X1_batch = X_batch[:, :title_len]\n",
    "        X2_batch = X_batch[:, title_len:]\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, lr:1e-5,\n",
    "                    batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "        predict_labels = sess.run(fetches, feed_dict)[0]\n",
    "        predict_scores.append(predict_labels)\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_scores = np.asarray(predict_scores)\n",
    "    return predict_labels_list, np.vstack(predict_scores)\n",
    "\n",
    "def write_result(predict_labels_list, result_path):\n",
    "    \"\"\"把结果写到 result.csv 中\"\"\"\n",
    "    eval_question = np.load('../data/eval_question.npy')\n",
    "    with open('../data/sr_topic2id.pkl', 'rb') as inp:\n",
    "        sr_topic2id = pickle.load(inp)\n",
    "        sr_id2topic = pickle.load(inp)\n",
    "    pred_labels = np.asarray(predict_labels_list).reshape([-1])\n",
    "    pred_topics = sr_id2topic[pred_labels].values.reshape([-1, 5])   # 转为 topic\n",
    "    df_result = pd.DataFrame({'question':eval_question, 'tid0': pred_topics[:,0], 'tid1':pred_topics[:, 1],\n",
    "                         'tid2': pred_topics[:,2], 'tid3':pred_topics[:,3],'tid4': pred_topics[:,4]})\n",
    "    df_result.to_csv(result_path, index=False, header=False)\n",
    "    print('Finished writing the result')\n",
    "    return df_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1min 19s, sys: 22.2 s, total: 1min 42s\n",
      "Wall time: 2min 7s\n",
      "Finished writing the result\n",
      "('len(df_result)=', 217360)\n",
      "Saving the predict_scores into ../scores/han-bigru-title-content-256-30.npy\n",
      "('predict_scores.shape=', (217360, 1999))\n",
      "Finished saving the result!\n"
     ]
    }
   ],
   "source": [
    "%time predict_labels_list,predict_scores = predict()\n",
    "df_result = write_result(predict_labels_list, result_path=result_path) \n",
    "print('len(df_result)=',len(df_result))  # 结果应该为 217360\n",
    "print('Saving the predict_scores into %s' % scores_path)\n",
    "print('predict_scores.shape=',predict_scores.shape)\n",
    "np.save(scores_path, predict_scores)\n",
    "print('Finished saving the result!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>tid0</th>\n",
       "      <th>tid1</th>\n",
       "      <th>tid2</th>\n",
       "      <th>tid3</th>\n",
       "      <th>tid4</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6215603645409872328</td>\n",
       "      <td>4610596224687453206</td>\n",
       "      <td>-7506384235581390893</td>\n",
       "      <td>-6306904715218704629</td>\n",
       "      <td>-6839713564940654454</td>\n",
       "      <td>-5932391056759866388</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6649324930261961840</td>\n",
       "      <td>-240041917918953337</td>\n",
       "      <td>2858911571784840089</td>\n",
       "      <td>3418451812342379591</td>\n",
       "      <td>-7483543763655495143</td>\n",
       "      <td>-212983527176510806</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-4251899610700378615</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-7358589937244777363</td>\n",
       "      <td>2816249700493135244</td>\n",
       "      <td>-7270992690764838239</td>\n",
       "      <td>-5265476641576484497</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>6213817087034420233</td>\n",
       "      <td>-4966205278807386328</td>\n",
       "      <td>-8655945395761165989</td>\n",
       "      <td>5804619920623030604</td>\n",
       "      <td>244937959911721367</td>\n",
       "      <td>7476760589625268543</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-8930652370334418373</td>\n",
       "      <td>3972493657017129406</td>\n",
       "      <td>-8963554618409314978</td>\n",
       "      <td>-1115593437686158905</td>\n",
       "      <td>7951349602759061249</td>\n",
       "      <td>-985918886318729368</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "               question                  tid0                  tid1  \\\n",
       "0   6215603645409872328   4610596224687453206  -7506384235581390893   \n",
       "1   6649324930261961840   -240041917918953337   2858911571784840089   \n",
       "2  -4251899610700378615   2919247920214845195  -7358589937244777363   \n",
       "3   6213817087034420233  -4966205278807386328  -8655945395761165989   \n",
       "4  -8930652370334418373   3972493657017129406  -8963554618409314978   \n",
       "\n",
       "                   tid2                  tid3                  tid4  \n",
       "0  -6306904715218704629  -6839713564940654454  -5932391056759866388  \n",
       "1   3418451812342379591  -7483543763655495143   -212983527176510806  \n",
       "2   2816249700493135244  -7270992690764838239  -5265476641576484497  \n",
       "3   5804619920623030604    244937959911721367   7476760589625268543  \n",
       "4  -1115593437686158905   7951349602759061249   -985918886318729368  "
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_result.head(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>tid0</th>\n",
       "      <th>tid1</th>\n",
       "      <th>tid2</th>\n",
       "      <th>tid3</th>\n",
       "      <th>tid4</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6215603645409872328</td>\n",
       "      <td>4610596224687453206</td>\n",
       "      <td>-7506384235581390893</td>\n",
       "      <td>-6306904715218704629</td>\n",
       "      <td>-6839713564940654454</td>\n",
       "      <td>2919247920214845195</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6649324930261961840</td>\n",
       "      <td>-240041917918953337</td>\n",
       "      <td>2858911571784840089</td>\n",
       "      <td>3418451812342379591</td>\n",
       "      <td>-7483543763655495143</td>\n",
       "      <td>2382911985227044227</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-4251899610700378615</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-7358589937244777363</td>\n",
       "      <td>2816249700493135244</td>\n",
       "      <td>-7270992690764838239</td>\n",
       "      <td>-5265476641576484497</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>6213817087034420233</td>\n",
       "      <td>-8655945395761165989</td>\n",
       "      <td>-4966205278807386328</td>\n",
       "      <td>5804619920623030604</td>\n",
       "      <td>7476760589625268543</td>\n",
       "      <td>244937959911721367</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-8930652370334418373</td>\n",
       "      <td>3972493657017129406</td>\n",
       "      <td>-8963554618409314978</td>\n",
       "      <td>-1115593437686158905</td>\n",
       "      <td>6018641953300645757</td>\n",
       "      <td>7951349602759061249</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "               question                  tid0                  tid1  \\\n",
       "0   6215603645409872328   4610596224687453206  -7506384235581390893   \n",
       "1   6649324930261961840   -240041917918953337   2858911571784840089   \n",
       "2  -4251899610700378615   2919247920214845195  -7358589937244777363   \n",
       "3   6213817087034420233  -8655945395761165989  -4966205278807386328   \n",
       "4  -8930652370334418373   3972493657017129406  -8963554618409314978   \n",
       "\n",
       "                   tid2                  tid3                  tid4  \n",
       "0  -6306904715218704629  -6839713564940654454   2919247920214845195  \n",
       "1   3418451812342379591  -7483543763655495143   2382911985227044227  \n",
       "2   2816249700493135244  -7270992690764838239  -5265476641576484497  \n",
       "3   5804619920623030604   7476760589625268543    244937959911721367  \n",
       "4  -1115593437686158905   6018641953300645757   7951349602759061249  "
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 参考结果\n",
    "df_result.head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在全部预测正确的情况下，理论值为：f1=0.713933\n",
    "precision=2.50273, recall=0.998873, f1=0.713933"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在全部预测正确的情况下，理论值为：\n",
      "precision=2.50273, recall=0.998873, f1=0.713933\n"
     ]
    }
   ],
   "source": [
    "# 假设全部正确，f1 值最高能到多少\n",
    "def padding_label(labels):\n",
    "    \"\"\"把所有的label补齐到长度为 5\"\"\"\n",
    "    label_len = len(labels)\n",
    "    if label_len >= 5:\n",
    "        return labels[:5]\n",
    "    return np.hstack([labels, np.zeros(5-label_len, dtype=int) - 1])\n",
    "    \n",
    "\n",
    "marked_labels_list = data_valid.y.tolist() # 所有的标注结果\n",
    "predict_labels_list = map(padding_label, marked_labels_list)\n",
    "predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "print '在全部预测正确的情况下，理论值为：'\n",
    "print 'precision=%g, recall=%g, f1=%g' % (precision, recall, f1)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [conda root]",
   "language": "python",
   "name": "conda-root-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
